import {
  getEhsStandardByPage,
  addEhsStandard,
  updateEhsStandard,
  delEhsStandard,
  exportEhsStandard,
} from '@/services/templateMaintain/ehsStandard';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Col, Form, Input, InputNumber, message, Modal, Row, Tooltip, Tree } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
const EhsStandard: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [theselectedRowKeys, settheSelectedRowKeys] = useState<React.Key[]>([]);
  //选中selection中的序号
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    settheSelectedRowKeys(newSelectedRowKeys);
    // console.log(newSelectedRowKeys);
  };
  const EHSStandard: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      sorter: true,
      valueType: 'index',
      width: 80,
    },
    /* {
      title: '唯一标识',
      dataIndex: 'identification',
      hideInTable: true,
    }, */
    {
      title: '模板编号',
      align: 'center',
      sorter: true,
      dataIndex: 'templateId',
    },
    {
      title: '检查项目',
      align: 'center',
      sorter: true,
      dataIndex: 'checkItem',
    },
    {
      title: '检查描述',
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'checkDesc',
      onCell: () => {
        return {
          style: {
            maxWidth: 100,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '是否有效',
      align: 'center',
      sorter: true,
      dataIndex: 'isValid',
    },
    {
      title: '顺序编号',
      align: 'center',
      sorter: true,
      search: false,
      dataIndex: 'sequence',
    },
    {
      title: '是否需要附件',
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'isAttached',
    },
    {
      title: '备注',
      search: false,
      align: 'center',
      sorter: true,
      dataIndex: 'notes',
      onCell: () => {
        return {
          style: {
            maxWidth: 100,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      // width: 238,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            form.setFieldsValue({
              identification: record.identification,
              checkItem: record.checkItem,
              checkDesc: record.checkDesc,
              isValid: record.isValid,
              templateId: record.templateId,
              sequence: record.sequence,
              isAttached: record.isAttached,
              notes: record.notes,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delEhsStandard({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values: any) => {
    setConfirmLoading(true);
    console.log('standard标题', values);
    if (formTitle == '新建') {
      const result = await addEhsStandard(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else if (formTitle == '编辑') {
      const result = await updateEhsStandard(values);
      if (result != null) {
        message.success('修改成功');
      }
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current?.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="EHS巡检模版"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 100,
          defaultCollapsed: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportEhsStandard({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `EHSStandard.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params };
          const sorters = sortTran(sort);
          const filters = filterTran(res);
          const result = await getEhsStandardByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          //getproductbop();
          //过滤后端传递的null数据
          const tableinfo3: any[] = [];
          result.data.content.map((item: any, index: number) => {
            if (item != null) {
              tableinfo3.push(item);
            }
          });
          console.log(result.data.content);
          console.log(tableinfo3);
          return {
            data: tableinfo3,
            total: tableinfo3.length,
            success: result.success,
          };
        }}
        columns={EHSStandard}
        scroll={{ x: 2000, y: 450 }}
        rowSelection={{ onChange: onSelectChange }}
      />

      <ModalForm
        form={form}
        title={formTitle}
        visible={modalVisit}
        onFinish={handleSubmit}
        confirmLoading={confirmLoading}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="identification"
          label="唯一标识"
          rules={[{ required: true, message: 'Please input your identification!' }]}
          disabled={createOrUpdate}
          initialValue={111}
          hidden={true}
        />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="templateId"
              label="模板编号"
              disabled={createOrUpdate}
              rules={[{ required: true, message: 'Please input!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="checkDesc"
              label="检查描述"
              disabled={createOrUpdate}
              rules={[{ required: true, message: 'Please input!' }]}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="checkItem"
              label="检查项目"
              disabled={createOrUpdate}
              rules={[{ required: true, message: 'Please input!' }]}
            />
          </Col>
          <Col span={12}>
            {/* <ProFormText
              name="sequence"
              label="顺序编号"
              disabled={createOrUpdate}
              rules={[{ required: true, message: 'Please input!' }]}
            /> */}
            <Form.Item
              label="顺序编号"
              name="sequence"
              style={{ width: 350 }}
              rules={[{ required: true, message: 'Please input!' }]}
            >
              <InputNumber
                // addonAfter="件"
                style={{ width: 350 }}
                min={0}
                max={99999}
                step={1}
                // onChange={(e) => handlestandManufactWorkHourChange(e.target.value)}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="isValid"
              label="是否有效"
              disabled={createOrUpdate}
              valueEnum={{
                是: '是',
                否: '否',
              }}
              rules={[{ required: true, message: 'Please input!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="isAttached"
              label="是否需要附件"
              disabled={createOrUpdate}
              rules={[{ required: true, message: 'Please input!' }]}
              valueEnum={{
                是: '是',
                否: '否',
              }}
            />
          </Col>
          <Col span={12}>
            {/* <ProFormText name="notes" label="备注" disabled={createOrUpdate} /> */}
          </Col>
        </Row>
        <ProFormTextArea
          name="notes"
          label="备注"
          // rules={[{ required: true, message: 'Please input notes!' }]}
          placeholder="请输入备注"
          fieldProps={{ width: '100%', showCount: true, maxLength: 100, rows: 3 }}
          // disabled={createOrUpdate}
        />
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default EhsStandard;
